package net.tv90.volunteerserveradmin.utils;

import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class SMSCodeUtils {

    private final Random random = new Random();
    private final String[] zeros = {"00000", "0000", "000", "00", "0", ""};

    @Resource
    private RedisUtils redisUtils;

    public String generateCodeForTel(String tel) {
        int hash = tel.hashCode();
        int encryption = 123456;
        long rehash = hash ^ encryption;
        long time = System.currentTimeMillis();
        rehash ^= time;
        long code = rehash % 1000000;
        code = code < 0 ? -code : code;
        String codeStr = code + "";
        int length = codeStr.length();
        String finalCode = zeros[length - 1] + codeStr;
        redisUtils.setObject("smsCode::tel::" + tel, finalCode, 5, TimeUnit.MINUTES);
        return finalCode;
    }

    public String generateCodeForEmail(String email) {
        int base = random.nextInt(0, Integer.MAX_VALUE) % 1000000;
        String codeStr = String.valueOf(base);
        int length = codeStr.length();
        String finalCode = zeros[length - 1] + codeStr;
        redisUtils.setObject("smsCode::email::" + email, finalCode, 5, TimeUnit.MINUTES);
        return finalCode;
    }

    public String getCodeFromCacheForTel(String tel) {
        return redisUtils.getObject("smsCode::tel::" + tel);
    }

    public String getCodeFromCacheForEmail(String email) {
        return redisUtils.getObject("smsCode::email::" + email);
    }


}